import { portalInstance } from '@/utils/request'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/dashboard/Index.vue'),
    },
    {
      path: '/user/:id',
      name: 'user',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/user/Portrait.vue'),
    },
    {
      path: '/merchant/:id',
      name: 'merchant',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/merchant/Portrait.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/auth/Index.vue'),
    },
  ],
})

router.beforeEach(async (to, from) => {
  const resp = await portalInstance.get('/getInfo')
  if (resp.data.code == 401 && to.name !== 'login') {
    // 将用户重定向到登录页面
    return { name: 'login' }
  }
})

export default router
